<template>
	<view class="content qa-content">
		<TopVue />
		<view class="qa-main">
			<YuyingVue :sayIng="sayFlag" :tipsWords="'按住下方语音按钮描述你的病症'" />
			<!-- <view style="text-align: center;font-size: 28rpx; color: #666;border-bottom: solid 1px #eee;">{{voiceOption.text}}</view> -->
			<!-- <scroll-view ref="scrollContainer" :scroll-top="scrollTop" scroll-y="true" class="msg-box"></scroll-view> -->
			<view class="msg-box">
				<view class="scroll-content">
					<view class="msg-list" v-for="(item,idx) in msgList" :key="'msglist_'+idx">
						<view class="my-msg" v-if="item.problem">
							<view class="my-msg-panel">{{item.problem}}</view>
							<!-- <view class="iconfont c-danger">&#xe74b; 删除</view> -->
						</view>
						<view class="msg-type">
							<view class="msg-type-panel" v-if="item.sendLoading">
								AI健康管家思考中
								<span class="sendIng">.</span>
								<span class="sendIng">.</span>
								<span class="sendIng">.</span>
							</view>
							<view class="msg-type-panel" v-else-if="item.isTimeout">
								服务器繁忙
							</view>
							<view class="msg-type-panel" v-else>
								<!-- 思考完成 -->
							</view>
						</view>
						<!-- <div class="msg-process"></div> -->
						<view class="msg-answer">
							<view class="answer-panel" v-show="item.answer">
								<!-- <view>{{item.answer}}</view> -->
								<zero-markdown-view :markdown="item.answer" ></zero-markdown-view>
								<view>
									<text class="suggestion" v-for="(suggestion,idx) in item.suggestion" :key="'answer_'+idx">{{suggestion}}</text>
								</view>
							</view>
						</view>
					</view>
				</view>
				
			</view>
				
			

			<view class="bottom-box">
				<view class="remind">选择症状快捷输入</view>
				<view class="easyAsking">
					<view class="tag" v-for="item in ['中风','痛风','偏头痛']"  :key="'answer_'+item" @click="voiceOption.content = item">{{item}}
					</view>
				</view>
				<!-- <view style="color: gainsboro;">{{pageType}}</view> -->
				<view class="bottom-input-box">
					<view class="bottom-btn" :class="loading ? 'button-disabled':'bottom-btn'" @longpress="voiceChat"
						@touchend="ontouchend">
						<text class="iconfont">&#xe905;</text>
					</view>
					<view style="width: 60%;">
						<uni-easyinput borderColor="#3AD3C1" v-model="voiceOption.content"
							placeholder="请输入您的问题"></uni-easyinput>
					</view>
					<view class="confirm-btn" @click="sendContent">发送</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import TopVue from '@/components/top.vue'
	import YuyingVue from '@/components/Yuying.vue'
	import commonApi from '@/common/api.ts'
	import config from "@/common/config"
	import permision from "@/untils/permission.js";
	import {
		getStorage
	} from "@/common/util"
	export default {
		components: {
			TopVue,
			YuyingVue
		},
		data() {
			return {
				answerList: [],
				msgList: [],
				answerTimmer: {},
				index: 0,
				countDown: null,
				voiceOption: {
					text: '',
					content: '',
				},
				innerAudioContext: null,
				recognition: null,
				sayFlag: false,
				loading: false,
				pageType: '',
				scrollTop: 0,
				scrollIng: false,
				memoryId: ''
			}
		},
		onLoad() {
			this.checkPermission()
		},
		methods: {
			scrollBottom() {
				if (this.scrollIng === true) return
				this.scrollIng = true
				setTimeout(() => {
					const query = uni.createSelectorQuery().in(this);
					query.select('.scroll-content').boundingClientRect(res => {
						if (res) {
							const contentHeight = res.height; // 内容高度（px）
							this.scrollTop = contentHeight
							this.scrollIng = false
						}
					}).exec();
				}, 500)


				//this.scrollTop = this.$refs.scrollContainer.$el.scrollHeight - this.$refs.scrollContainer.$el.clientHeight;
			},
			async checkPermission() {
				// #ifdef MP-WEIXIN || MP-ALIPAY || MP-BAIDU || MP-TOUTIAO
				// 小程序端直接初始化录音管理器，无需权限请求
				this.recognition = uni.getRecorderManager()
				this.recognition.onStop((res) => {
					this.pageType = '录音结束';
					this.loading=false;
					this.voice2Text(res.tempFilePath)
				})
				// #endif

				// #ifdef APP-PLUS
				// App端需要请求权限
				const status = await permision.requestAndroidPermission('android.permission.RECORD_AUDIO');
				if (status === -1) { // 用户拒绝
					uni.showModal({
						content: '未授权麦克风权限，点击确认跳转设置页',
						success: () => permision.gotoAppPermissionSetting()
					});
				} else {
					this.recognition = uni.getRecorderManager()
					this.recognition.onStop((res) => {
						this.pageType = '录音结束';
						this.voice2Text(res.tempFilePath)
					})
				}
				// #endif
			},
			ontouchend() {
				this.pageType = '抬起了按钮';
				if (this.voiceOption.text === "抬起发送") {
					this.loading = true
					uni.showLoading({
						mask: true
					})
					this.sayFlag = false
					this.voiceOption.text = "AI健康管家正在回复您..."
					setTimeout(() => {
						//this.sendContent()
						this.recognition.stop();
						uni.hideLoading()
					}, 300)
				}
			},
			//请求后端接口将语音转为文字
			async voice2Text(tempFilePath) {
				uni.uploadFile({
					name: 'file',
					url: config.apiUrl + '/chat/translate',
					filePath: tempFilePath,
					success: (res) => {
						this.pageType = '文件上传成功';
						this.voiceOption.content = res.data
						uni.hideLoading()
						this.sendContent()
					},
					fail: (err) => {
						this.pageType = '文件上传失败';
						console.log('上传失败：', err);
					}
				})
			},
			showAnswer(key) {
				if (this.answerTimmer[key]) return;
				let data = ''

				this.answerTimmer[key] = setTimeout(() => {
					this.answerList[key].reduce((prev, item, index) => {
						if (item === '') {
							item = ' '
						}
						if (item !== '#' && this.answerList[key][index + 1] === '#' && this.answerList[key]
							[index + 2] === '#' && this.answerList[key][index + 3] === '#') {
							item = item + '<br/>'
						}
						if (item === '#' && this.answerList[key][index - 2] === '#' && this.answerList[key]
							[index - 1] === '#') {
							item = item + '<br/>'
						}
						if (item === '-' && prev === ' ') {
							item = "<br/>-"
						}
						data += item
					}, '')
					let answer = data

					this.msgList[key].markerHtml = ''
					let that = this
					this.msgList[key].answer = ''
					printOneByOne()
					setTimeout(() => {
						this.answerTimmer[key] = null
						this.content = ''
					}, 3000)
					uni.hideLoading()

					function printOneByOne() {
						if (that.index >= data.length) {
							that.index = 0
							that.answerTimmer[key] = null
							that.content = ''
						} else {
							setTimeout(() => {
								that.msgList[key].answer += answer[that.index]
								that.index++
								printOneByOne()
								that.scrollBottom()
							}, 30)
						}
					}
				}, 500);
			},
			//语音输入后请求后端接口
			voiceChat() {
				this.pageType = '开始语音输入'
				this.sayFlag = true
				this.voiceOption.text = '抬起发送'
				if (this.recognition) {
					this.recognition.start({
						format: 'mp3',
						sampleRate: 16000,
						numberOfChannels:1
					})
					this.voiceOption.text = '抬起发送'
				} else {
					uni.showToast({
						icon: 'error',
						title: '您的设备不支持录音'
					})
					this.hideLoading()
				}
			},
			//将语音输入的参数传给后端
			async sendContent() {
				let userAuth = getStorage('userAuth') || {}
				let qus = this.voiceOption.content
				if (!qus) {
					uni.showToast({
						title: '您好像没有说话，请长按按钮询问问题',
						icon: 'none',
					})
					this.loading = false
					this.voiceOption.text = '请按住语音输入'
					return
				}
				this.showQus(qus)
				this.scrollBottom()
				const key = this.msgList.length - 1;
				// 请求
				this.pageType = '发送问题给后台'
				// this.$refs['chatSSEClientRef'].startChat({
				// 	url: config.apiUrl +
				// 		`/chat/plantChatStream?message=${qus}&memoryId=${this.memoryId}&ifNetworking=是`,
				// 	// 请求头
				// 	headers: {
				// 		token: userAuth.token ? userAuth.token : ''
				// 	},
				// 	// 默认为 post
				// 	method: 'get',
				// 	body: {}
				// })
				// return
				uni.request({
					url: config.apiUrl +`/chat/plantChatStream?message=${qus}&memoryId=${this.memoryId}&ifNetworking=是`,
					method: 'GET',
					header: {
						token:userAuth.token ? userAuth.token : ''
					},
					success: (res) => {
						console.info(res)
						this.pageType = '获取到后台返回结果'
						if (res && res.data) {
							let resText = res.data
							this.answerList = []
							if (this.answerList[key]) {
								this.answerList[key].push(resText);
							} else {
								this.answerList[key] = [resText]
							}
							this.msgList[key].sendLoading = false
							this.showAnswer(key)
							this.voiceOption.text=''
							return
						}
					},
					fail: (err) => {
						uni.showToast({
							'title': '请求接口失败',
							'duration': 2000,
							'icon': 'none'
						})
					}
				})
				return







				// const res = await commonApi.AIVoiceChat(qus, this.memoryId)
				// this.pageType = '获取到后台返回结果'
				// if (res && res.text) {
				// 	let resText = res.text
				// 	this.answerList = []
				// 	if (this.answerList[key]) {
				// 		this.answerList[key].push(resText);
				// 	} else {
				// 		this.answerList[key] = [resText]
				// 	}
				// 	this.msgList[key].sendLoading = false
				// 	this.showAnswer(key)

				// 	const base64Data = res.audio
				// 	const tempDir = '_doc'
				// 	const tempFilePath = `${tempDir}/temp_audio.wav`;
				// 	plus.io.resolveLocalFileSystemURL(tempDir, (dirEntry) => {
				// 		dirEntry.getFile(
				// 			"temp_audio.wav", {
				// 				create: true,
				// 				exclusive: false
				// 			},
				// 			(fileEntry) => {
				// 				fileEntry.createWriter((writer) => {
				// 					writer.onwriteend = () => {

				// 						this.innerAudioContext = uni.createInnerAudioContext();
				// 						this.innerAudioContext.autoplay = true;
				// 						this.innerAudioContext.src = tempFilePath
				// 						this.innerAudioContext.onPlay(() => {
				// 							this.voiceOption.content = ''
				// 						});
				// 						this.innerAudioContext.onError((res) => {
				// 							console.log(res.errMsg);
				// 						});
				// 						this.innerAudioContext.onEnded((res) => {
				// 							this.loading = false
				// 							this.voiceOption.text = '请按住语音输入'
				// 						})
				// 						uni.hideLoading()
				// 					};
				// 					writer.onerror = (err) => {
				// 						console.info(err)
				// 					}
				// 					writer.writeAsBinary(base64Data);
				// 				});
				// 			}
				// 		);
				// 	}, (err) => {
				// 		console.info(err)
				// 	});
				// } else {
				// 	uni.showToast({
				// 		title: res,
				// 		icon: 'error'
				// 	})
				// 	uni.hideLoading()
				// }
			},
			//停止语音
			stopChat() {
				if (this.innerAudioContext) {
					this.innerAudioContext.stop()
				}
			},
			//语音输入语音回复的问答展示
			showQus(qus) {
				this.msgList.push({
					problem: qus + "",
					answer: "",
					sendLoading: true,
					isTimeout: false,
				});
			},
		}
	}
</script>
<style lang="scss">
	.sendIng {
		display: inline-block;
		font-size: 56rpx;
		line-height: 0;
	}

	.sendIng:nth-child(1) {
		animation: sendIngAnimation 2s linear 0.5s infinite;
	}

	.sendIng:nth-child(2) {
		animation: sendIngAnimation 2s linear 1s infinite;
	}

	.sendIng:nth-child(3) {
		animation: sendIngAnimation 2s linear 1.5s infinite;
	}

	@keyframes sendIngAnimation {
		0% {
			transform: translateY(0);
			opacity: 1;
		}

		25% {
			transform: translateY(-10rpx);
			opacity: 1;
		}

		50% {
			transform: translateY(0);
			opacity: 1;
		}

		75% {
			transform: translateY(10rpx);
			opacity: 1;
		}

		100% {
			transform: translateY(0);
			opacity: 1;
		}
	}

	.qa-content {
		height: 100%;

		.qa-main {
			padding: 0 20rpx;
			background-color: #F6F6F6;
			min-height: calc(100% - 100rpx);
			display: flex;
			flex-direction: column;
		}

		.msg-box {
			padding-bottom: 300rpx;
			//height: 30vh;
			flex-grow: 1;
			//overflow: auto;

			.my-msg {
				text-align: right;
			}

			.msg-answer,
			.my-msg {
				font-size: 28rpx;
				font-weight: bold;
				color: #1E1E1E;
				padding: 10rpx 0rpx;
			}

			.answer-panel,
			.my-msg-panel {
				text-align: left;
				padding: 10rpx 20rpx;

				max-width: 80%;
				display: inline-block;
			}

			.my-msg-panel {
				background: rgba(0, 122, 255, 0.2);
				border-radius: 20rpx 0 20rpx 20rpx;
			}

			.answer-panel {
				background: #FFFFFF;
				border: 1rpx solid rgba(16, 53, 151, 0.1);
				border-radius: 0rpx 20rpx 20rpx 20rpx;
			}

			.iconfont {
				font-weight: lighter;
				font-size: 26rpx;
				margin-top: 10rpx;
			}

			.suggestion {
				font-weight: 400;
				font-size: 13rpx;
				color: #2F65F3;
				margin-right: 5rpx;
			}

			.goods-parent {
				min-width: 600rpx;
			}

			.goods-paneltitle {
				font-weight: 500;
				font-size: 16rpx;
				color: #1E1E1E;
				margin-top: 20rpx;
				margin-bottom: 10rpx;
			}

			.goods-list {
				display: inline-flex;
				align-items: center;
				background-color: #EDEDED;
				padding: 5rpx;
				border-radius: 4rpx;
				width: 250rpx;
				margin-right: 10rpx;
				margin-borrom: 10rpx;
			}

			.goods-img {
				width: 100rpx;
				height: 100rpx;
				margin-right: 5rpx;
				flex-shrink: 0;
			}

			.goods-title {
				font-weight: 500;
				font-size: 14rpx;
				color: #1E1E1E;
				margin-bottom: 10rpx;
			}

			.goods-info {
				font-size: 12rpx;
				color: #4E4E4E;
				font-weight: lighter;
			}
		}

		.bottom-box {
			position: fixed;
			bottom: 0rpx;
			width: 100%;
			left: 0;
			padding: 20rpx 20rpx 20rpx 20rpx;
			background-color: #ffffff;

			.bottom-input-box {
				display: flex;
				align-items: center;
				justify-content: space-between;
			}

			.remind {
				margin-bottom: 20rpx;
				font-size: 24rpx;
				color: #d3d4d8;
			}

			.easyAsking {
				display: flex;
				align-items: center;
				flex-wrap: wrap;
				margin: 20rpx 0;

				.tag {
					padding: 10rpx;
					background-color: #F2F3F8;
					border-radius: 40rpx;
					width: 136rpx;
					margin: 10rpx;
					text-align: center;
					font-size: 28rpx;
					color: #666;
				}
			}

			.bottom-btn {
				width: 80rpx;
				border-radius: 50%;
				color: #fff;
				background-color: #3AD3C1;
				display: flex;
				align-items: center;
				justify-content: center;
				height: 80rpx;
				-webkit-user-select: none;
				-moz-user-select: none;
				-ms-user-select: none;
				user-select: none;
				-webkit-touch-callout: none;

				.iconfont {
					font-size: 32rpx;
				}
			}

			.button-disabled {
				background-color: #dedede;
				pointer-events: none;
			}

			.confirm-btn {
				box-sizing: border-box;
				background-color: #3AD3C1;
				text-align: center;
				border-radius: 34rpx;
				padding: 20rpx;
				width: 140rpx;
				line-height: 30rpx;
				color: #FFFFFF;

			}
		}
	}
</style>